package com.huanglejing.shanggou.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.afollestad.materialdialogs.GravityEnum
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.common.BaseActivity
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.DisplayUtils
import com.huanglejing.shanggou.utils.FileUtil
import com.huanglejing.shanggou.view.largeImage.ImageGestureListener
import com.huanglejing.shanggou.view.largeImage.MultiTouchZoomableImageView

import kotlinx.android.synthetic.main.activity_watch_large_image.*
import java.io.File


class WatchLargeImageActivity : BaseActivity() {

    private val URLList: ArrayList<String> by lazy { intent.getStringArrayListExtra(INTENT_IMAGE_URL) }
    private val imageViewList by lazy { setImageParams() }

    private val index: Int by lazy { intent.getIntExtra(FLAGSTRING, -1) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_watch_large_image)
        initWidget()
    }



    private fun initWidget() {
        vp_largeImage.adapter = MyViewPagerAdapter(imageViewList, URLList, this)
        if (index != -1) {
            vp_largeImage.currentItem = index
        } else {
            vp_largeImage.currentItem = 0
        }
    }

    fun setImageParams() = URLList.mapIndexed { index, s ->

        val param = ViewPager.LayoutParams()
        param.gravity = Gravity.CENTER_VERTICAL
        if (DisplayUtils.isScreenOriatationPortrait(this@WatchLargeImageActivity)) {
            param.width = DisplayUtils.`$width`()
            param.height = DisplayUtils.`$width`() * 3 / 4
        } else {
            param.width = DisplayUtils.`$height`()
            param.height = DisplayUtils.`$width`()
        }
        if (s.endsWith(".gif")) {
            val imageview = ImageView(this@WatchLargeImageActivity)
            imageview.layoutParams = param
            imageview.scaleType=ImageView.ScaleType.CENTER_INSIDE
            imageview.setOnClickListener { finish() }
            imageview.setOnLongClickListener {
                MaterialDialog.Builder(this@WatchLargeImageActivity).cancelable(false).content(resources.getString(R.string.str_save))
                        .buttonsGravity(GravityEnum.CENTER).titleGravity(GravityEnum.CENTER).contentGravity(GravityEnum.CENTER)
                        .positiveText(resources.getString(R.string.str_confirm1)).negativeText(resources.getString(R.string.str_cancle)).onPositive(MaterialDialog.SingleButtonCallback { dialog, which ->

                            Glide.with(this).load(s).downloadOnly(object : SimpleTarget<File>() {
                                override fun onResourceReady(resourece: File?, glideAnimation: GlideAnimation<in File>?) {
                                    val filePath = C.Cache.EX_IMAGE_DICM
                                    val fileName = "${System.currentTimeMillis()}${Math.random().times(1000).toInt()}.gif"
                                    var copyTo = resourece?.copyTo(File("${filePath}${fileName}"))
                                    // 其次把文件插入到系统图库

                                    // 最后通知图库更新
                                    this@WatchLargeImageActivity.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://${copyTo?.getAbsolutePath()}")))
                                    Toast.makeText(this@WatchLargeImageActivity, resources.getString(R.string.str_pic_save), Toast.LENGTH_LONG).show()
                                }
                            })
                            //   FileUtil.saveImageToGallery(this@WatchLargeImageActivity, C.Cache.EX_IMAGE_DIR, imageview)
                        }).onNegative { dialog, which ->
                            dialog.dismiss()
                        }.show()
                return@setOnLongClickListener true
            }
            imageview
        } else {
            val matrxImage = MultiTouchZoomableImageView(this@WatchLargeImageActivity)

            matrxImage.layoutParams = param

            onImageViewFound(matrxImage)
            matrxImage.setBackgroundColor(resources.getColor(R.color.black))

            matrxImage
        }
    }


    // 设置图片点击事件
    private fun onImageViewFound(imageView: MultiTouchZoomableImageView) {
        imageView.setImageGestureListener(object : ImageGestureListener {

            override fun onImageGestureSingleTapConfirmed() {
                finish()
            }

            override fun onImageGestureLongPress() {
                MaterialDialog.Builder(this@WatchLargeImageActivity).cancelable(false).content(resources.getString(R.string.str_save))
                        .buttonsGravity(GravityEnum.CENTER).titleGravity(GravityEnum.CENTER).contentGravity(GravityEnum.CENTER)
                        .positiveText(resources.getString(R.string.str_confirm1)).negativeText(resources.getString(R.string.str_cancle)).onPositive(MaterialDialog.SingleButtonCallback { dialog, which ->
                            FileUtil.saveImageToGallery(this@WatchLargeImageActivity, C.Cache.EX_IMAGE_DIR, imageView.imageBitmap)
                        }).onNegative { dialog, which ->
                            dialog.dismiss()
                        }.show()
            }

            override fun onImageGestureFlingDown() {
                finish()
            }
        })
    }


    companion object {

        private val INTENT_IMAGE_URL = "INTENT_IMAGE_URL"
        private val FLAGSTRING = "currentIndex"
        @JvmStatic
        fun startShow(context: Context, url: List<String>, index: Int? = null) {
            val list: ArrayList<String> = url as? ArrayList ?: ArrayList(url)
            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putStringArrayListExtra(INTENT_IMAGE_URL, list)
            intent.setClass(context, WatchLargeImageActivity::class.java)
            intent.putExtra(FLAGSTRING, index ?: -1)
            context.startActivity(intent)
        }
    }

    class MyViewPagerAdapter(private val mListViews: List<View>, private val imageData: List<String>, private val context: Context)//构造方法，参数是我们的页卡，这样比较方便。
        : PagerAdapter() {

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(mListViews[position])//删除页卡
        }


        override fun instantiateItem(container: ViewGroup, position: Int): Any {  //这个方法用来实例化页卡
            container.addView(mListViews[position], 0)//添加页卡
            if (imageData[position].endsWith(".gif")) {
                Glide.with(context).load(imageData[position])
                        .placeholder(R.drawable.ic_img_error)
                        .error(R.drawable.ic_img_error)
                        .thumbnail(0.1f)
                        .into((mListViews[position] as? ImageView))
            } else {
                Glide.with(context).load(imageData[position]).asBitmap()
                        .dontAnimate()
                        .placeholder(R.drawable.ic_img_error)
                        .error(R.drawable.ic_img_error)
                        .into(object : SimpleTarget<Bitmap>() {

                            private var loading = MaterialDialog.Builder(context).content(R.string.loading).progress(true, 0).cancelable(true).build()

                            override fun onLoadStarted(placeholder: Drawable?) {
                                super.onLoadStarted(placeholder)
                                loading = loading.builder.show()
                            }

                            override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
                                loading.dismiss()
                                (mListViews[position] as? MultiTouchZoomableImageView)?.let {
                                    it?.imageBitmap = resource
                                } ?: (mListViews[position] as? ImageView)?.let {
                                    it?.setImageBitmap(resource)
                                }

                                // drawable = resource
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {
                                super.onLoadCleared(placeholder)
                                loading.dismiss()

                            }

                            override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) {
                                super.onLoadFailed(e, errorDrawable)
                                loading.dismiss()
                                // drawable = BitmapFactory.decodeResource(AppContext.get().resources, R.drawable.load_img_error)
                                (mListViews[position] as? MultiTouchZoomableImageView)?.let {
                                    val decodeResource = BitmapFactory.decodeResource(AppContext.get().resources, R.drawable.load_img_error)
                                    it?.imageBitmap = decodeResource
                                } ?: (mListViews[position] as? ImageView)?.let {
                                    it?.setImageResource(R.drawable.load_img_error)
                                }
                            }
                        })
            }

            return mListViews[position]
        }

        override fun getCount(): Int {
            return mListViews.size//返回页卡的数量
        }

        override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
            return arg0 === arg1//官方提示这样写
        }
    }

}
